package com.gzc.just.play.last.war.gateserver.handler;

import com.gzc.just.play.last.war.common.annotation.MessageHandler;
import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;
import com.gzc.just.play.last.war.common.serializer.MessageSerializer;
import com.gzc.just.play.last.war.common.serializer.SerializerFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Handler for client connections.
 * Processes messages from Unity client and routes them to appropriate handlers.
 * Note: This handler is now integrated with VirtualThreadNettyServer framework.
 */
@Component
@MessageHandler(serverTypes = {MessageHandler.ServerType.GATE_SERVER})
public class ClientConnectionHandler implements SimpleMessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(ClientConnectionHandler.class);
    
    private final ConcurrentHashMap<Long, ChannelHandlerContext> authenticatedClients;
    private MessageSerializer messageSerializer;
    
    public ClientConnectionHandler() {
        this.authenticatedClients = new ConcurrentHashMap<>();
        // Delay serializer initialization to avoid circular dependencies
        this.messageSerializer = null;
    }
    
    /**
     * Lazy initialization of message serializer
     */
    private MessageSerializer getMessageSerializer() {
        if (messageSerializer == null) {
            messageSerializer = SerializerFactory.getSerializer();
        }
        return messageSerializer;
    }

    /**
     * 处理连接建立事件
     * Note: This method is now called by VirtualThreadNettyServer when a new connection is established.
     */
    public void handleConnectionEstablished(ChannelHandlerContext ctx) {
        logger.info("Client connected: {}", ctx.channel().remoteAddress());
    }
    
    /**
     * 处理连接关闭事件
     * Note: This method is now called by VirtualThreadNettyServer when a connection is closed.
     */
    public void handleConnectionClosed(ChannelHandlerContext ctx) {
        logger.info("Client disconnected: {}", ctx.channel().remoteAddress());
        
        // Remove from authenticated clients
        Long sessionId = ctx.channel().attr(ClientAttributes.SESSION_ID).get();
        if (sessionId != null) {
            authenticatedClients.remove(sessionId);
        }
    }
    
    /**
     * 添加到已认证客户端列表
     */
    public void addAuthenticatedClient(Long sessionId, ChannelHandlerContext ctx) {
        authenticatedClients.put(sessionId, ctx);
        logger.debug("Added authenticated client with session ID: {}", sessionId);
    }
    
    /**
     * 从已认证客户端列表中移除
     */
    public void removeAuthenticatedClient(Long sessionId) {
        authenticatedClients.remove(sessionId);
        logger.debug("Removed authenticated client with session ID: {}", sessionId);
    }
    
    /**
     * 获取已认证客户端数量
     */
    public int getAuthenticatedClientCount() {
        return authenticatedClients.size();
    }

    @Override
    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {
        // This handler doesn't directly process messages
        // It's used for connection management only
        logger.debug("ClientConnectionHandler.handle called, but this handler only manages connections");
    }
    
    @Override
    public int getMessageId() {
        // This handler doesn't handle specific message types
        return -1;
    }
    
    @Override
    public String getName() {
        return "ClientConnectionHandler";
    }
    
    @Override
    public Logger getLogger() {
        return logger;
    }
}